package cn.com.nes.site.action.user;

import cn.com.nes.common.baiduface.BaiduApis;
import cn.com.nes.common.util.*;
import cn.com.nes.site.entity.*;
import cn.com.nes.site.entity.sms.VerCodeReq;
import cn.com.nes.site.module.dao.UserConnDaoImpl;
import cn.com.nes.site.module.service.UserService;
import cn.com.nes.site.module.service.crm.ClueService;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.ProtocolType;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import static cn.com.nes.common.util.Globals.*;

@Controller("public")
@RequestMapping("/public")
public class PublicAction {
	
	@Resource
	private ClueService service_clue;

    @Resource
    private UserService userService;

    @RequestMapping(method = RequestMethod.GET, value = "/ossRoleArn")
    public @ResponseBody
    PageData ossRoleArn(HttpServletRequest request, HttpServletResponse response,
                        ModelMap modelMap) throws FileNotFoundException {
        DataRes reqStatus = DBUtils.setRemoteVisit(request, response, false);
        PageData res;
        if (reqStatus.getRetCode() != 0) {
            res = new PageData();
            res.setRetCode(reqStatus.getRetCode());
            res.setRetMessage(reqStatus.getRetMessage());
            return res;
        }

        String policy = OssRoleArnUtils.readJson(request);
        String roleSessionName = "alice-001";
        long durationSeconds = 900;
        // 此处必须为 HTTPS
        ProtocolType protocolType = ProtocolType.HTTPS;
        res = new PageData();
        Map<String, Object> respMap = new LinkedHashMap<String,Object>();
        res.setData(respMap);
        try {
            final AssumeRoleResponse stsResponse = OssRoleArnUtils.assumeRole(Globals.uploadAccessKeyID,
                    accessKeySecretRoleArn, Globals.roleArn, roleSessionName, policy,
                    protocolType, durationSeconds);
            respMap.put("StatusCode", "200");
            respMap.put("AccessKeyId", stsResponse.getCredentials().getAccessKeyId());
            respMap.put("AccessKeySecret", stsResponse.getCredentials().getAccessKeySecret());
            respMap.put("SecurityToken", stsResponse.getCredentials().getSecurityToken());
            respMap.put("Expiration", stsResponse.getCredentials().getExpiration());
            res.setRetCode(0);
            res.setRetMessage("OK");
        } catch (ClientException e) {
            respMap.put("StatusCode", "500");
            respMap.put("ErrorCode", e.getErrCode());
            respMap.put("ErrorMessage", e.getErrMsg());
            res.setRetCode(9);
            res.setRetMessage(e.getErrMsg());
        }

        return res;
    }

    @RequestMapping(method = RequestMethod.GET, value = "/getImgSignURL")
    public @ResponseBody
    PageData getImgSignURL(HttpServletRequest request, HttpServletResponse response,
                           ModelMap modelMap) throws FileNotFoundException {
        DataRes reqStatus = DBUtils.setRemoteVisit(request, response, false);
        PageData res;
        if (reqStatus.getRetCode() != 0) {
            res = new PageData();
            res.setRetCode(reqStatus.getRetCode());
            res.setRetMessage(reqStatus.getRetMessage());
            return res;
        }

        HashMap<String, Object> reqData = reqStatus.getReq().getReqData();
        String isYs = (String) reqData.get("isYs");
        String objectName = (String) reqData.get("objectName");
        String urlStr = OssUtil.getImgSignURL(objectName, Integer.parseInt(isYs));
        OssImageDto dto = new OssImageDto();
        dto.setImageRealUrl(urlStr);

        res = new PageData();
        Map<String, Object> respMap = new LinkedHashMap<String,Object>();
        respMap.put("oss", dto);
        res.setData(respMap);
        res.setRetCode(0);
        res.setRetMessage("OK");
        return res;
    }

    @RequestMapping(method = RequestMethod.GET, value = "/getImgSignURLForCall")
    public @ResponseBody
    PageData getImgSignURLForCall(HttpServletRequest request, HttpServletResponse response,
            ModelMap modelMap) throws FileNotFoundException {
        DataRes reqStatus = DBUtils.setRemoteVisit(request, response, false);
        PageData res;
        if (reqStatus.getRetCode() != 0) {
            res = new PageData();
            res.setRetCode(reqStatus.getRetCode());
            res.setRetMessage(reqStatus.getRetMessage());
            return res;
        }

        HashMap<String, Object> reqData = reqStatus.getReq().getReqData();
        String isYs = (String) reqData.get("isYs");
        String objectName = (String) reqData.get("objectName");
        String urlStr = OssUtil.getImgSignURL(objectName, Integer.parseInt(isYs), Globals.bucketName_call);
        OssImageDto dto = new OssImageDto();
        dto.setImageRealUrl(urlStr);

        res = new PageData();
        Map<String, Object> respMap = new LinkedHashMap<String,Object>();
        respMap.put("oss", dto);
        res.setData(respMap);
        res.setRetCode(0);
        res.setRetMessage("OK");
        return res;
    }

    @RequestMapping(method = RequestMethod.GET, value = "/getFileSignURL")
    public @ResponseBody
    PageData getFileSignURL(HttpServletRequest request, HttpServletResponse response,
                            ModelMap modelMap) throws FileNotFoundException {
        DataRes reqStatus = DBUtils.setRemoteVisit(request, response, false);
        PageData res = new PageData();
        res.setRetCode(9);
        if (reqStatus.getRetCode() != 0) {
            res = new PageData();
            res.setRetCode(reqStatus.getRetCode());
            res.setRetMessage(reqStatus.getRetMessage());
            return res;
        }

        String objectName = (String) reqStatus.getReq().getReqData().get("fileName");
        if (StrUtil.isEmpty(objectName)) {
            res.setRetMessage("下载的文件不能为空");
            return res;
        }
        //判断是否是Excel文件
        if (!objectName.matches("^.+\\.(?i)(xls)$") && !objectName.matches("^.+\\.(?i)(xlsx)$")) {
            res.setRetMessage("不是Excel文件,请检查后,再重新操作");
            return res;
        }
        //创建OSSClient实例
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        //设置URL过期时间为1小时
        Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
        //生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容
        URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
        String urlStr = url.toString();
        //关闭OSSClient
        ossClient.shutdown();

        res = new PageData();
        Map<String, Object> respMap = new LinkedHashMap<String,Object>();
        respMap.put("oss", urlStr);
        res.setData(respMap);
        res.setRetCode(0);
        res.setRetMessage("OK");
        return res;
    }


    @RequestMapping(method = RequestMethod.GET, value = "/getFileURL")
    public @ResponseBody PageData getFileURL(HttpServletRequest request, HttpServletResponse response,
                                             ModelMap modelMap) {
        DataRes reqStatus = DBUtils.setRemoteVisit(request, response, false);
        PageData res = new PageData();
        res.setRetCode(9);
        if (reqStatus.getRetCode() != 0) {
            res = new PageData();
            res.setRetCode(reqStatus.getRetCode());
            res.setRetMessage(reqStatus.getRetMessage());
            return res;
        }

        String objectName = (String) reqStatus.getReq().getReqData().get("objectName");

        OSSClient ossClient = null;
        String urlStr = "";
        try {
            //创建oss客户端
            ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            //定义过期时间
            Date expiration = new Date(System.currentTimeMillis() + 5 * 60 * 1000);
            //判断文件是否存在
            boolean found = ossClient.doesObjectExist(bucketName, objectName);
            if (found) {
                //生成签名以后的URL
                GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.GET);
                //
                req.setExpiration(expiration);
                req.addQueryParameter("t", String.valueOf(System.currentTimeMillis()));
                URL signedUrl = ossClient.generatePresignedUrl(req);
                urlStr = signedUrl.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        res = new PageData();
        Map<String, Object> respMap = new LinkedHashMap<String,Object>();
        respMap.put("ossURL", urlStr);
        res.setData(respMap);
        res.setRetCode(0);
        res.setRetMessage("OK");
        return res;
    }

    @RequestMapping(method = RequestMethod.GET, value = "/getOss_Sign")
    public @ResponseBody PageData getOss_Sign(HttpServletRequest request, HttpServletResponse response,
                                             ModelMap modelMap) {
        DataRes reqStatus = DBUtils.setRemoteVisit(request, response, false);
        PageData res = new PageData();
        res.setRetCode(9);
        if (reqStatus.getRetCode() != 0) {
            res = new PageData();
            res.setRetCode(reqStatus.getRetCode());
            res.setRetMessage(reqStatus.getRetMessage());
            return res;
        }

        DataReq req = reqStatus.getReq() ;
		try{
			String dir = (String) req.getReqData().get("ossPath");
			
			if(StringUtils.isEmpty(dir)){
				res.setRetCode(0);
				res.setRetMessage("文件上传路径为空");
				return res;
			}
			
			
			String host = "http://" + Globals.bucketName + "."+ Globals.endpoint_nohttp;
			
			OSS client  = new OSSClientBuilder().build(endpoint, Globals.uploadAccessKeyID, accessKeySecretRoleArn);
        	
			long expireTime = 30;
			long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
			Date expiration = new Date(expireEndTime);
			PolicyConditions policyConds = new PolicyConditions();
			policyConds.addConditionItem(
					PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
			policyConds.addConditionItem(MatchMode.StartWith,
					PolicyConditions.COND_KEY, dir);
			
			String postPolicy = client.generatePostPolicy(expiration,
					policyConds);
			
			byte[] binaryData = postPolicy.getBytes("utf-8");
			String encodedPolicy = BinaryUtil.toBase64String(binaryData);
			String postSignature = client.calculatePostSignature(postPolicy);
			
			Map<String, Object> respMap = new LinkedHashMap<String, Object>();
			respMap.put("accessid", Globals.uploadAccessKeyID);
			respMap.put("policy", encodedPolicy);
			respMap.put("signature", postSignature);
			// respMap.put("expire", formatISO8601Date(expiration));
			respMap.put("dir", dir);
			respMap.put("host", host);
			respMap.put("expire", String.valueOf(expireEndTime / 1000));
			
			res.setData(respMap);
			res.setRetCode(0);
			res.setRetMessage("OK");
			//UserLogic.SaveSyslog(req.getUinfo().getUserid(), "查询q", "查询成功", "systemset/getOss_Sign", Globals.LOG_TYPE4, conn);
		}catch(Exception e){
			e.printStackTrace();
			res.setRetCode(0);
			res.setRetMessage("ERROR");
		}
		return res;
    }
    
    @RequestMapping(method = RequestMethod.GET, value = "/getImgData")
    public @ResponseBody PageData getImgData(HttpServletRequest request, HttpServletResponse response,
                                             ModelMap modelMap) {
        DataRes reqStatus = DBUtils.setRemoteVisit(request, response, true);
        PageData res = new PageData();
        res.setRetCode(9);
        if (reqStatus.getRetCode() != 0) {
            res = new PageData();
            res.setRetCode(reqStatus.getRetCode());
            res.setRetMessage(reqStatus.getRetMessage());
            return res;
        }

        DataReq req = reqStatus.getReq() ;
		try{
			String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/business_license?access_token={accessToken}";
			String API_Key = "KF20gfsZwX1wvQ2uImwciAdR" ;
			String Secret_Key = "nvMzLDSF06xU3YmLzv1s5bEO5FoqMWY2" ;
			ObjectNode result = BaiduApis.getToken(API_Key, Secret_Key);
			if(result.has("error")) {
				throw new RuntimeException(result.get("error").asText() + ": " + result.get("error_description").asText());
			}
			String accessToken ="" ;
			if(result.has("access_token")) {
				accessToken = result.get("access_token").asText();
			}
		     
			String imgurl = (String) req.getReqData().get("imgurl");

			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_JSON);
			HttpEntity<String> requestBai = new HttpEntity<String>("url="+imgurl, headers);
			RestTemplate template = new RestTemplate();
			ObjectNode BaiDuRes = template.postForObject(url, requestBai, ObjectNode.class, accessToken);
			res.setExtData(BaiDuRes);
			res.setRetCode(0);
			res.setRetMessage("OK");
		}catch(Exception e){
			e.printStackTrace();
			res.setRetCode(0);
			res.setRetMessage("ERROR");
		}
		return res;
    }
    
    //文件下载
    @RequestMapping(method = RequestMethod.GET, value = "/downloadFile")
    public @ResponseBody
    PageData downloadCustomerFile(HttpServletRequest request,
                      HttpServletResponse response, ModelMap modelMap,@RequestParam("fileUrl") String fileUrl, @RequestParam("fileName") String fileName) throws Exception {
        DataRes req_Status = DBUtils.setRemoteVisit(request, response,false);
        PageData res = new PageData() ;
        if (req_Status.getRetCode() != 0) {
            res = new PageData();
            res.setRetCode(req_Status.getRetCode()) ;
            res.setRetMessage(req_Status.getRetMessage());
            return res;
        }
        try {
            URL url = new URL(fileUrl);
            System.out.println(fileUrl);
            int index = fileUrl.indexOf("?");//第一个问号的位置
            if(index > -1) {
                fileUrl = fileUrl.substring(0, index);
            }
            String[] split = fileUrl.split("\\.");
            // 不同文件的MimeType参考后续链接
            response.setContentType("application/x-download");//下面三行是关键代码，处理乱码问题
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso8859-1") + "." + split[split.length-1]);
            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            OutputStream fos = response.getOutputStream();
            // 读取路径下面的文件
            FileCopyUtils.copy(inStream, fos);
            response.getOutputStream().flush();
            response.getOutputStream().close();
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }
    
    @RequestMapping(method = RequestMethod.GET, value = "/sendActivityCode")
    public @ResponseBody PageData sendActivityCode(HttpServletRequest request, HttpServletResponse response,
                                             ModelMap modelMap) throws SQLException {
        DataRes reqStatus = DBUtils.setRemoteVisit(request, response, false);
        PageData res = new PageData();
        res.setRetCode(9);
        if (reqStatus.getRetCode() != 0) {
            res = new PageData();
            res.setRetCode(reqStatus.getRetCode());
            res.setRetMessage(reqStatus.getRetMessage());
            return res;
        }

        DataReq req = reqStatus.getReq() ;
        Map<String, String> map = new LinkedHashMap<String, String>();
		PageData restmp = service_clue.getActivityByID(req) ;
		if(restmp.getRetCode()!=0) {
			res.setRetCode(1) ;
			res.setRetMessage("没有查询到该活动信息！");
			return res ;
		}
		
		map.put("product", (String)restmp.getData().get("name")) ;
		if(StringUtils.isEmpty((String)restmp.getData().get("subname"))) {
			map.put("item", "签到") ;
		}else {
			map.put("item", (String)restmp.getData().get("subname")) ;
		}
		//数据库查找
        VerCodeReq sms = SMSUtil.sendActivityCode((String)req.getReqData().get("phone"),map) ;
        if (sms != null){
            userService.InsertSmsCode(sms);
            res.setRetCode(0);
            res.setRetMessage("获取验证码成功！");
        }else{	res.setRetCode(9);
            res.setRetMessage("获取验证码失败");
        }
		return res;
    }   
    
	//落地页添加数据
	@RequestMapping(method = RequestMethod.POST, value = "/addClue")
	public @ResponseBody  PageData addClue(HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap) throws Exception {
			DataRes req_Status = DBUtils.setRemoteVisit(request, response,false);
			PageData res = new PageData() ;
			if (req_Status.getRetCode() != 0) {
				res = new PageData();
				res.setRetCode(req_Status.getRetCode()) ;
				res.setRetMessage(req_Status.getRetMessage());
				return res;
			}
			
			DataReq req = req_Status.getReq() ;
			PageData restmp = service_clue.getActivityByID(req) ;
			if(restmp.getRetCode()!=0) {
				res.setRetCode(1) ;
				res.setRetMessage("没有查询到该活动信息！");
				return res ;
			}
			
			String code = (String)req.getReqData().get("verCode") ;
			String phone = (String)req.getReqData().get("phone") ;
//			if(!ValidCodeUtil.validCode(phone, code)) {
//				res.setRetCode(1) ;
//				res.setRetMessage("验证码错误！");
//				return res ;
//			}
        //数据库查找
        UserConnDaoImpl userConnDaoImpl = new UserConnDaoImpl();
        long validCode = userConnDaoImpl.VerificationCode(phone, code);
        if (validCode == 0) {
            res.setRetCode(9);
            res.setRetMessage("验证码输入错误!");
            return res;
        } else if (validCode < 0) {
            res.setRetCode(9);
            res.setRetMessage("验证码过期!");
            return res;
        }
			
			req.getReqData().put("followupstatus", "01") ; //跟进状态
			req.getReqData().put("poolentrymode", "05") ; //线索池
			req.getReqData().put("culestate", "02") ; //线索状态，新线索
			req.getReqData().put("cluestage", "01") ; //跟进状态
			req.getReqData().put("cluesource", restmp.getData().get("cluesource")) ; //跟进状态
			req.getReqData().put("pooltype",  "其他") ;
			String xzqhdm = service_clue.getAreaCodeByPhone(req);
			req.getReqData().put("xzqhdm",xzqhdm) ;
			req.getReqData().put("isRl","0") ;
			req.getReqData().put("cluename", req.getReqData().get("companyName")) ;
			req.getReqData().put("cluebelongtocompany", restmp.getData().get("companyId")) ;
			req.getReqData().put("advertisementId",restmp.getData().get("uuid")) ;
			req.getReqData().put("cluecompany", req.getReqData().get("companyName")) ;
			req.getReqData().put("companycontact",req.getReqData().get("nickname")) ;
			if(StringUtils.isEmpty((String)req.getReqData().get("companycontact"))) {
				req.getReqData().put("companycontact",req.getReqData().get("name")) ;
			}
			req.getReqData().put("cluephone", phone) ;
			req.getReqData().put("projectaddress",null) ;
			req.getReqData().put("numberhome", req.getReqData().get("province")) ;
			
			//保存其他扩展字段
			String json = JsonUtil.getStriFromObj(req.getReqData());
			req.getReqData().put("otherdata",json) ;
			
			UserInfo uinfo = new UserInfo();
			uinfo.setId((String)restmp.getData().get("createUid"));
			uinfo.setCompanyId((String)restmp.getData().get("companyId"));
			req.setUinfo(uinfo );
			res = service_clue.addClue(req) ;
			return res;
	}

	// 获取商城token
    @RequestMapping(method = RequestMethod.POST, value = "/getShopToken")
    public @ResponseBody  PageData getShopToken(HttpServletRequest request,
                                             HttpServletResponse response, ModelMap modelMap) throws Exception {
        DataRes req_Status = DBUtils.setRemoteVisit(request, response,false);
        PageData res = new PageData() ;
        if (req_Status.getRetCode() != 0) {
            res = new PageData();
            res.setRetCode(req_Status.getRetCode()) ;
            res.setRetMessage(req_Status.getRetMessage());
            return res;
        }

        DataReq req = req_Status.getReq() ;
        res = userService.getShopToken(req);
        return res;
    }

    // 获取广告列表
    @RequestMapping(method = RequestMethod.POST, value = "/getAdList")
    public @ResponseBody  PageData getAdList(HttpServletRequest request,
                                           HttpServletResponse response, ModelMap modelMap) throws Exception {
        DataRes req_Status = DBUtils.setRemoteVisit(request, response,false);
        PageData res = new PageData() ;
        if (req_Status.getRetCode() != 0) {
            res = new PageData();
            res.setRetCode(req_Status.getRetCode()) ;
            res.setRetMessage(req_Status.getRetMessage());
            return res;
        }

        DataReq req = req_Status.getReq() ;
        res = service_clue.getAdList(req);
        return res;
    }
    
}
